﻿using Consul;
using Microsoft.Extensions.Options;

namespace Demo.ProductService.Registrys;

/// <summary>
/// 服务注册类
/// </summary>
public class ConsulServiceRegistry
{
    public ServiceRegistryOptions serviceRegistryOptions;
    public ConsulServiceRegistry(IOptions<ServiceRegistryOptions> options)
    {
        this.serviceRegistryOptions = options.Value;
    }


    /// <summary>
    /// 服务注册
    /// </summary>
    public void Registry()
    {
        // 1、创建consul服务器连接
        var consulClient = new ConsulClient(configuration =>
        {
            //1.1 填写consul服务地址
            configuration.Address = new Uri(serviceRegistryOptions.ConsulAddress);
        });

        // 2、创建服务地址
        var uri = new Uri(serviceRegistryOptions.ServiceAddress);

        // 3、注册服务地址
        //3.1、准备AgentServiceRegistration
        var registration = new AgentServiceRegistration
        {
            ID = serviceRegistryOptions.ServiceID,
            Name = serviceRegistryOptions.ServiceName,
            Address = uri.Host, //IP地址
            Port = uri.Port, //端口号
            Tags = new string[] { },
            Check = new AgentServiceCheck //心跳焦侧机制： 检测微服务是否正常
            {
                // 3.2、设置consul健康检查超时间10秒
                Timeout = TimeSpan.FromSeconds(10),
                // 3.3、服务停止30秒后注销服务
                DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(30),
                // 3.4、consul健康检查地址
                HTTP = serviceRegistryOptions.HealthCheckAddress,
                // 3.5 consul健康检查间隔时间
                Interval = TimeSpan.FromSeconds(10),
            }
        };
        //3.6、注册服务地址
        consulClient.Agent.ServiceRegister(registration).Wait();

        Console.WriteLine($"微服务地址注册成功：{serviceRegistryOptions.ServiceAddress}");
    }

    /// <summary>
    /// 删除注册
    /// </summary>
    public void DeRegistry()
    { 
        // 1、创建consul服务器连接
        var consulClient = new ConsulClient(configuration =>
        {
            //1.1 填写consul服务地址（http://localhost:8500/）
            configuration.Address = new Uri(serviceRegistryOptions.ConsulAddress);
        });
        //2、服务删除
        consulClient.Agent.ServiceDeregister(serviceRegistryOptions.ServiceID).Wait();

        Console.WriteLine($"微服务地址删除成功：{serviceRegistryOptions.ServiceAddress}");

    }

}
